import axios from 'axios'
import dayjs from 'dayjs'
import { ElLoading } from 'element-plus'
let loading //定义loading变量

function startLoading() {
    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)',
    })
}
function endLoading() {
    //使用Element loading-close 方法
    loading.close()
}

//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0
export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}
let instance = axios.create({
    //baseURL: '/api',
    transformRequest: [
        function(data) {
            Date.prototype.toISOString = function() {
                return dayjs(this).format('YYYY-MM-DDTHH:mm:ssZ')
            }
            data = JSON.stringify(data)
            return data
        },
    ],
})
 //axios.defaults.baseURL = '/api' //此路径为配置代理服务器时的代理路径

//http request 拦截器
instance.interceptors.request.use(
    config => {
        showFullScreenLoading()
        return config
    },
    // eslint-disable-next-line no-unused-vars
    error => {
        // eslint-disable-next-line no-undef
        return Promise.reject(err)
    }
)

//http response 拦截器
instance.interceptors.response.use(
    response => {
        tryHideFullScreenLoading()
        return response
    },
    error => {
        tryHideFullScreenLoading()
        return Promise.reject(error)
    }
)

export default {
    async get(url, params, config) {
        const response = await instance.get(url, {
            params,
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
                withCredentials: true,
                auth: 'jhecis',
            },
            ...config,
        })
        return response
    },

    async post(url, data, config) {
        const response = await instance.post(url, data, {
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
                withCredentials: true,
                auth: 'jhecis',
            },
            ...config,
        })
        return response
    },
}
